package com.xinsmartsky.penmaji.penmaji;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.xinsmartsky.penmaji.NewGridView.NewGridView;
import com.xinsmartsky.penmaji.SerialPort.FileOperation;

import java.util.Arrays;

public class ChineseMixActivity extends Activity implements View.OnClickListener, AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
    private int MatLastNum = 16;//最后设置的矩阵个数
    private LinearLayout chinese_lin_gridview;
    private HorizontalScrollView chinese_hs_gview;
    private Button chinese_btn_back;
    private EditText chinese_edt_pinyin = null;
    private TextView chinese_tv_title = null;
    private NewGridView newGridView;
    private int height;
    private int devfd = -1;
    private Button chmix_btn_write = null;
    private Button chinmix_btn_del;//删除
    private EditText chinmix_edt_test = null;
    private ArrayAdapter<String> adapter;
    private static String[] matrix = new String[]{"点阵", "12 X 12", "16 X 16"};
    private SerialPortActivity start_serialport = new SerialPortActivity();
    private byte[] ArrayC = new byte[]{};
    private EditText chinese_edt_zfgd;//高度
    private EditText chinese_edt_zk;//宽度
    private Spinner chinmix_spi_dz;
    private int num;//字条
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chinese_mix);
        devfd = getIntent().getIntExtra("fd", 0);
        num = getIntent().getIntExtra("num", 0);
        Log.i("fd", "fd-------------------------------------" + devfd);
        FindViewById();
        setOnClickListener();
        lin_drawview();
    }

    private void FindViewById() {
        chinmix_spi_dz = (Spinner)findViewById(R.id.chinmix_spi_dz);
        adapter = new ArrayAdapter<String>(ChineseMixActivity.this, android.R.layout.simple_spinner_item, matrix);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        chinmix_spi_dz.setAdapter(adapter);
        chinmix_spi_dz.setOnItemSelectedListener(this);
        chinese_edt_zk = (EditText)findViewById(R.id.chinese_edt_zk);
        chinese_edt_zfgd = (EditText)findViewById(R.id.chinese_edt_zfgd);
        chinmix_edt_test = (EditText) findViewById(R.id.chinmix_edt_test);
        chmix_btn_write = (Button) findViewById(R.id.chmix_btn_write);
        ((Button)findViewById(R.id.chinmix_btn_del)).setOnClickListener(this);
        chinese_tv_title = (TextView) findViewById(R.id.chinese_tv_title);
        chinese_tv_title.requestFocus();
        chinese_lin_gridview = (LinearLayout) findViewById(R.id.chinese_lin_gridview);
        chinese_hs_gview = (HorizontalScrollView) findViewById(R.id.chinese_hs_gview);
        chinese_btn_back = (Button) findViewById(R.id.chinese_btn_back);
        //文本变化监听器----监听拼音输入完成状态
        chinmix_edt_test.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            //一个字母调用一次
            @Override
            public void afterTextChanged(Editable s) {
                //在afterTextChanged中， 调用setText()方法会重新触发监听器， 并不断进行递归，最后程序崩溃，需合理退出递归
                if (s.length() > 0) {
                    String str = chinmix_edt_test.getText().toString();
                    //画点阵
                    newGridView = new NewGridView(ChineseMixActivity.this);
                    Log.i("vvv", "---------------------------------------------------------------------------");
                    //str:字符串;  MatLastNum:点阵数  chinese_lin_gridview:linerlayout
                    str = "今天没有雾霾";
                    Log.i("ddd", "汉字3是================" + str + MatLastNum);
                    ArrayC = newGridView.ChineseShow(str, MatLastNum, chinese_lin_gridview);
                }
            }
        });
    }

    private void setOnClickListener() {
        chmix_btn_write.setOnClickListener(this);
        chinese_lin_gridview.setOnClickListener(this);
        chinese_btn_back.setOnClickListener(this);
    }

    private void lin_drawview() {
        if (chinese_lin_gridview.getChildCount() > 0) {
            chinese_lin_gridview.removeAllViews();
        }
        for (int i = 0; i < 100; i++) {
            chinese_lin_gridview.addView(DrawGridView());
        }
    }


    //删除按钮
    public void delete() {
        int lastnum = newGridView.getlastnum(chinese_lin_gridview);
        Log.i("qqq", "lastnum = " + lastnum);
        if(lastnum < 0){//没有有图的
            ;
        }else {
            chinese_lin_gridview.removeViewAt(lastnum);//删除最后一个有汉字的
            //从数组中删除
//        ？？？？？？？？？？？？？？？？
            chinese_lin_gridview.addView(DrawGridView());
        }
    }

    /*画网格布局*/
    private View DrawGridView() {
        final NewGridView edit_ngv_newview;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 5, 0, 0);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.activity_edit_item, null);
        edit_ngv_newview = (NewGridView) view.findViewById(R.id.edit_ngv_newview);
        //触屏时设置不滑动
        edit_ngv_newview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    chinese_hs_gview.requestDisallowInterceptTouchEvent(false);
                } else {
                    chinese_hs_gview.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
        chinese_hs_gview.requestDisallowInterceptTouchEvent(false);
        //设置网格参数 画网格的时候要画16 * 16,因为12 * 12的数组有32个字节
                edit_ngv_newview.setPort_num(16);
                edit_ngv_newview.setHOR_num(16);
                ViewTreeObserver vto = edit_ngv_newview.getViewTreeObserver();
                vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        edit_ngv_newview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        height = edit_ngv_newview.getHeight();
                        float fheight = (float) (height / ((float) 16));
                        edit_ngv_newview.setLength(fheight);

                    }
                });
        view.setLayoutParams(lp);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chinese_btn_back: {
                this.finish();
                break;
            }
            case R.id.chinmix_btn_del:{
                delete();
                break;
            }
                //写入串口
            case R.id.chmix_btn_write: {
                SerialPortActivity start_serialport = new SerialPortActivity();
                FileOperation fileOperation = new FileOperation();
                //遍历出字条的实际长度
                int practicelen = 0;
                for (int k = 0; k < chinese_lin_gridview.getChildCount(); k++) {
                    NewGridView gridView = (NewGridView) (chinese_lin_gridview.getChildAt(k)).findViewById(R.id.edit_ngv_newview);
                    if (gridView.getTag() != null) {
                        practicelen ++;
                    }
                }
                //设置字条号
                int type = 1;//表示字条
                fileOperation.SetArrayToAddress(type, num, ArrayC, practicelen);//向文件中写入信息
                start_serialport.SendDataBlock(devfd);
                fileOperation.PrintData();
                break;
            }
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //spinner字体设置
        TextView tv = (TextView) view;
        tv.setTextSize(30.0f);
        tv.setGravity(Gravity.CENTER_HORIZONTAL);//设置居中

        switch (position) {
            case 0: {
                break;
            }
            case 1: {
                MatLastNum = 12;
                lin_drawview();
                break;
            }
            case 2: {
                MatLastNum = 16;
                lin_drawview();
                break;
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}
